package cn.js189.uqc.service.impl;

import cn.js189.common.util.Utils;
import cn.js189.common.util.exception.BSException;
import cn.js189.uqc.transform.IBSResponseTransformNew;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * 套餐使用情况查询 --> 量本使用查询 AccuUseQry-controller/AccuUseQry
 */
@Slf4j
@Component
public class AccuServiceUseQryTransformServiceImpl implements IBSResponseTransformNew {

	@Override
	public JSONObject transform(String responseString, String appendResponseString, String tranId) {
		try {

			log.debug("量本使用查询 accuUseQry 开始出参转换");

			JSONObject resObj = Utils.checkBillResponse(responseString, "resultCode", "resultMsg", "0");

			JSONArray offerInstInfo = resObj.getJSONArray("offerInstInfo");

			JSONArray cumulationList = new JSONArray();

			if (null != offerInstInfo && !offerInstInfo.isEmpty()) {

				for (int i = 0; i < offerInstInfo.size(); i++) {

					JSONObject offerInst = offerInstInfo.getJSONObject(i);

					JSONArray accuQryList = offerInst.getJSONArray("accuQryList");

					if (null != accuQryList && !accuQryList.isEmpty()) {

						for (int j = 0; j < accuQryList.size(); j++) {

							JSONObject cumulationObj = new JSONObject();

							JSONObject accuQryInfo = accuQryList.getJSONObject(j);

							cumulationObj.put("startTime", accuQryInfo.getString("beginTime"));
							cumulationObj.put("cumulationAlready", this.formatStringToDouble(new BigDecimal(accuQryInfo.getDoubleValue("usageVal"))));
							cumulationObj.put("unitName", this.getUnitNameByTypeId(accuQryInfo.getString("unitTypeId")));
							cumulationObj.put("accuName", accuQryInfo.getString("accuTypeName"));
							String ratableResourceId = accuQryInfo.getString("accuTypeAttr");
							cumulationObj.put("flag1", this.getFlag1(ratableResourceId));
							cumulationObj.put("endTime", accuQryInfo.getString("endTime"));
							cumulationObj.put("offerName", offerInst.getString("offerName"));
							cumulationObj.put("offerId", offerInst.getString("offerId"));
							cumulationObj.put("offerInstId", offerInst.getString("offerInstId"));
							cumulationObj.put("cumulationTotal", this.formatStringToDouble(new BigDecimal(accuQryInfo.getDoubleValue("initVal"))));
							// remoteRetType字段新接口无对应，暂设为0000
							cumulationObj.put("remoteRetType", "0000");
							cumulationObj.put("ratableResourceId", ratableResourceId);
							cumulationObj.put("cumulationLeft", this.formatStringToDouble(new BigDecimal(accuQryInfo.getDoubleValue("accuVal"))));
														
							//新增 流量阈值字段
							cumulationObj.put("thresholdValue", accuQryInfo.getString("thresholdValue"));

							cumulationList.add(cumulationObj);
						}
					}
				}
			}

			JSONObject responseBody = new JSONObject();

			responseBody.put("cumulationList", cumulationList);

			// 附加国漫节点
			if (!StringUtils.isEmpty(appendResponseString)) {

				JSONObject gmRes = JSON.parseObject(appendResponseString);

				String resultCode = gmRes.getString("resultCode");

				if (StringUtils.equals("200", resultCode)) {

					JSONArray gmOfferInstInfo = gmRes.getJSONArray("offerInstInfo");

					responseBody.put("offerInstInfo", gmOfferInstInfo);

				} else {

					// 国漫查询失败, key为gmResponse防止冲突
					responseBody.put("gmResponse", gmRes);
				}
			}

			log.debug("量本使用查询 accuUseQry 出参转换成功");

			return Utils.dealSuccessRespWithBodyAndTranId(tranId, responseBody);

		} catch (BSException e) {
			log.error("量本使用查询 accuUseQry 参数转换 BSException: {}", e.getErrorMsg());
			return Utils.dealBaseAppExceptionRespNew(tranId, e.getErrorMsg(), e.getErrorCode());
		} catch (Exception e) {
			log.error("量本使用查询 accuUseQry 参数转换 Exception: {}", e.getMessage());
			return Utils.dealExceptionRespNew(tranId);
		}
	}

	/**
	 * 根据类型获取单位名称
	 * 0 – 分（金额）
	 * 1 – 分钟（时长）
	 * 2 – 条
	 * 3 – 流量（KB）
	 */
	private String getUnitNameByTypeId(String typeId) {

		String unitName;

		switch (typeId) {
			case "0": unitName = "分"; break;
			case "1":  unitName = "分钟"; break;
			case "2":  unitName = "条"; break;
			case "3":  unitName = "KB"; break;
			default: unitName = ""; break;
		}

		return unitName;
	}

	/**
	 * 流量不清零标识
	 */
	private String getFlag1(String ratableResourceId) {
		char flag = ratableResourceId.charAt(2);
		return (flag == '2' || flag == '5') ? "1" : "0";
	}

	private String formatStringToDouble(Object object) {
		DecimalFormat df = new DecimalFormat("#0.00");
		return df.format(object);
	}

}
